<?php

/*
	info: 缓存函数库
*/

if (!defined('WEBINROOT'))
{
	header("HTTP/1.0 404 Not Found");
	exit();
}

if (defined('CACHE_FUNC'))
{
	return;
}
define('CACHE_FUNC', TRUE);


//获取缓存文件
//$intStripPath 是否去掉绝对地址前部
function cache_GetCacheFile($strFile, $intStripPath = 1)
{
	if ($intStripPath==1)
	{
		$strFile = preg_replace("/^".preg_quote(WEBFILEPATH, '/')."/", "", $strFile);
	}
	$filepath = dirname($strFile);
	$filename = basename($strFile);
	if ($filepath=='' || $filepath=='.')
	{
		$filepath = WEBFILEPATH.'/cache/system';
	}
	elseif ($filepath=='/' || $filepath=='\\')
	{
		$filepath = WEBFILEPATH;
	}
	elseif (substr($filepath, 0, 1)=='/')
	{
		$filepath = WEBFILEPATH.$filepath;
	}
	else
	{
		$filepath = WEBFILEPATH.'/cache/system/'.$filepath;
	}
	if (global_FileExt($filename)=='')
	{
		$filename = 'cache_'.$filename.'.php';
	}
	return "{$filepath}/{$filename}";
}

//转换为变量
function cache_GetCacheVars($data, $type = 'VAR')
{
	$evaluate = '';
	foreach ($data as $key => $val)
	{
		if (is_array($val))
		{
			$evaluate .= "\$webcache['$key'] = ".cache_GetCacheVarsFormat($val).";\n\n";
		}
		else
		{
			$val = addcslashes($val, '\'\\');
			$evaluate .= $type == 'VAR' ? "\$webcache['$key'] = '$val';\n" : "define('".strtoupper($key)."', '$val');\n";
		}
	}
	return $evaluate;
}

//数组显示格式化
function cache_GetCacheVarsFormat($array, $level = 0)
{
	$space = '';
	for ($i=0; $i<=$level; $i++)
	{
		$space .= "\t";
	}
	$evaluate = "array\n$space(\n";
	$comma = $space;
	foreach ($array as $key => $val)
	{
		$key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
		$val = !is_array($val) ? '\''.addcslashes($val, '\'\\').'\'' : $val;
		if (is_array($val))
		{
			$evaluate .= "$comma$key => ".cache_GetCacheVarsFormat($val, $level+1);
		}
		else
		{
			$evaluate .= "$comma$key => $val";
		}
		$comma = ",\n$space";
	}
	$evaluate .= "\n$space)";
	return $evaluate;
}

/**
 * 写入缓存文件
 * @param $strFile 缓存文件
 * @param $strCacheData 缓存数据
 * @param $bolPhpCode 是否是PHP格式
 * @param $bolAdd 是否在原文件末尾追加内容
 * @param $bolStop 是否错误后立即停止
 * @return bool 或者 直接停止显示错误
 */
function cache_Write($strFile, $strCacheData, $bolPhpCode = TRUE, $bolAdd = FALSE, $bolStop = TRUE)
{
	if ($strFile != '')
	{
		$strFile = cache_GetCacheFile($strFile);
		$tempOpenMode = ($bolAdd) ? 'ab' : 'wb';
		if (global_CreateFolder(dirname($strFile)) && @$fp=fopen($strFile, $tempOpenMode))
		{
			flock($fp, LOCK_EX);
			if ($bolPhpCode)
			{
				fwrite($fp, "<?php\n\n!defined('WEBINROOT') and exit();\n\n{$strCacheData}\n?>");
			}
			else
			{
				fwrite($fp, $strCacheData);
			}
			flock($fp, LOCK_UN);
			fclose($fp);
			@chmod($strFile, 0777);
			return TRUE;
		}
		elseif ($bolStop)
		{
			exit('Can not write cache file: '.basename($strFile).'.');
		}
	}
	return FALSE;
}
